(function (global, factory) {
  if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = global.document
      ? factory(global, true)
      : function (w) {
        if (!w.document) {
          throw new Error('需要在浏览器环境下执行');
        }
        return factory(w);
      };
  } else if (typeof define === 'function' && define.amd) {
    define('winMonitor', [], function () {
      return winMonitor;
    });
  } else {
    factory(global);
  }
})(typeof window !== 'undefined' ? window : this, function factory(
  window,
  noGlobal
) {

  function winMonitor(config = {}) {
    const { url, method, type } = config;
    this.url = url || 'http://172.16.6.211:9200/frontend/event/1';
    this.method = method || 'PUT';
    this.type = type || 'event';
  }

  winMonitor.prototype.vuePlugin = function () {
    let _this = this
    return {
      install: function (Vue, options) {
        Vue.prototype.$dispatchEvent = function (eventId, params, callback) {
          _this.dispatch(eventId, params, callback)
        }
      }
    }
  }

  winMonitor.prototype.dispatch = function (eventId, params, callback) {
    if (this.type === 'event') {
      this.eventSend(eventId, params, callback);
    } else if (this.type === 'hybrid') {
      this.hybridSend(eventId, params, callback);
    } else {
      this.eventSend(eventId, params, callback);
      this.hybridSend(eventId, params, callback);
    }
  };

  //简易ajax
  winMonitor.prototype.ajax = function (param, callback) {
    var xmlHttp = window.XMLHttpRequest
      ? new XMLHttpRequest()
      : new ActiveXObject('Microsoft.XMLHTTP');

    xmlHttp.open(this.method, this.url, true);

    xmlHttp.setRequestHeader('Content-Type', 'application/json')
    xmlHttp.onreadystatechange = function () {
      //待处理
      xmlHttp.onreadystatechange = function () {
        let response = {
          status: xmlHttp.status,
          response: JSON.parse(xmlHttp.response)
        }
        if (xmlHttp.readyState === 4 && xmlHttp.status) {
          typeof callback === 'function' && callback(response)
        } else {
          typeof callback === 'function' && callback(response)
        }
      }
    };
    xmlHttp.send(JSON.stringify(param));
  };

  //事件采集发送
  winMonitor.prototype.eventSend = function (eventId, params, callback) {
    this.ajax(Object.assign({}, params, { eventId }));
  };

  // 混合框架事件发送
  winMonitor.prototype.hybridSend = function (eventId, params, callback) {
    if (typeof winning !== 'undefined') {
      winning.dispatchEvent(eventId, params, callback);
    } else {
      console.error('未注册winning');
    }
  };

  if (!noGlobal) {
    window.zwMonitor = zwMonitor;
  }

});
